//
//  SpotCreateViewController.m
//  DigiOps
//
//  Created by app on 2018/7/26.
//  Copyright © 2018年 俞渊华. All rights reserved.
//

#import "SpotCreateViewController.h"
#import "SpotCreateViewCell.h"
#import "SpotSiteViewController.h"
#import "SpotPtiorityViewController.h"
#import "SpotUserViewController.h"
#import "SpotCalenderViewController.h"
#import "SpotModel.h"
#import "SopTextViewController.h"

#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "LYSDatePickerController.h"
#import "UserSites.h"
#import "HomeViewController.h"
@interface SpotCreateViewController ()
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *scoreArray;
@property(nonatomic, strong)NSMutableArray *titleArray;
@property(nonatomic, strong)NSDate* startDate;
@property(nonatomic, strong)NSString* commentTxt;
@property(nonatomic,strong)UserInfo* selectUser;
@property(nonatomic,strong)UserSites* selectSite;
@property(nonatomic,strong)NSMutableDictionary* selectText;

@end

@implementation SpotCreateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.tableView];
    
    self.scoreArray=[NSMutableArray new];
    self.titleArray=[NSMutableArray new];
    self.scoreArray=@[@"1.站点",@"2.优先级",@"3.执行人",@"4.建议开始时间",@"5.备注事项"];
    //    self.titleArray=@[@"1.选检查点",@"2.选优先级",@"3.选分配者",@"4.开始时间",@""];
    self.titleArray=[NSMutableArray arrayWithObjects:@"选择站点",@"选择优先级",@"选择执行人",@"选择建议开始时间",@"请在此处输入", nil];
    self.selectText=[NSMutableDictionary new];
    
    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"创建" style:UIBarButtonItemStyleBordered target:self action:@selector(postUI)];
    [myButton setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = myButton;
    
    //默认block方法：设置上拉加载更多
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
    //    label.shadowColor = [UIColor blackColor];
    //    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=@"临时任务";
    self.navigationItem.titleView = label;
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}


-(void)searchAticle{
    
}
-(void)postUI{
    if (![MySingleton sharedMySingleton].network) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"请检查网络状态" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }

    if (!self.startDate)
    {
        [SVProgressHUD showInfoWithStatus:@"亲,请选择开始时间"];
        return;
    }
    if (!self.commentTxt) {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入备注事项"];
        return;
    }
//    if ([user.text isEqualToString:@""])
//    {
//        //[SVProgressHUD showInfoWithStatus:@"亲,请输入用户名"];
//        return;
//    }
    for (NSDictionary* site in [UserInfo share].sites) {
        UserSites* s=[UserSites mj_objectWithKeyValues:site];
        NSLog(@"");
    }
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    //时区问题多8小时问题
    NSDateFormatter *isoFormat1 = [[NSDateFormatter alloc] init];
    [isoFormat1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    NSString *timeString = @"Sun Sep 13 11:43:04 +0800 2015";
    
    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    
    format.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
    
    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    format.timeZone = sourceTimeZone;
    
    NSDate *date = [format dateFromString:[isoFormat1 stringFromDate:self.startDate]];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localDate = [date dateByAddingTimeInterval:-interval];//减掉8小时，代码不得不这么写了
    
    NSLog (@"date: %@", localDate );
    NSLog (@"date: %@", self.startDate );
    

    //原来时间代码
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
//    [isoFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];

    int p=0;
    if (self.titleArray.count>0) {
        if ([self.titleArray[1] isEqualToString:@"优先级高"]) {
            p=2;
        }
        else
            p=1;
    }
    NSDictionary *params = @{
                             @"loginMaching" : [MySingleton sharedMySingleton].registrationID,
                             @"siteUuid" : self.selectSite.uuid,
                             @"assignUserUuid" : self.selectUser.uuid,
                             @"proposalStartTime" : [isoFormat stringFromDate:localDate],
                             @"workOrderRemark" : self.commentTxt,
                             @"priority" : @(p)
                             };
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"digiops/app/workOrder/InertWorkOrder" params:params success:^(id responseObj) {
        NSLog(@"");
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
//                [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"临时任务创建成功" withTime:1.0];
        HomeViewController * homeVC = [[HomeViewController alloc]init];
        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
        // 添加为子控制器
        nav.title = @"任务箱";
        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
//        //角色
//        UserRole* role=[UserRole mj_objectWithKeyValues:responseObj[@"result"][@"role"]];
//        [self.role setTitle:role.roleName forState:UIControlStateNormal];
//        //用户
//        UserInfo* user=[UserInfo mj_objectWithKeyValues:responseObj[@"result"]];
//        self.user=user;
//        //站点
//        for (NSDictionary* site in self.user.sites) {
//            UserSites* s=[UserSites mj_objectWithKeyValues:site];
//            NSLog(@"");
//        }
        //        rootViewController = nav;
    } failure:^(NSError *error) {
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)clickEvent{
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               [self postUI];
                                                           }];
}
- (NSArray *) titles {
    return @[@"创建临时任务"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.scoreArray.count;
    //    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SpotCreateViewCell* cell=[SpotCreateViewCell cellWithTableView:tableView];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;

    cell.spotTitle.text=[self.scoreArray objectAtIndex:indexPath.row];
    cell.spotContent.text=[self.titleArray objectAtIndex:indexPath.row];
    [cell.spotContent setTextColor:[UIColor lightGrayColor]];

    SpotModel* model=[[SpotModel alloc] init];
    model.ID=indexPath.row;
    cell.model=model;
    if (indexPath.row==4) {
        if (self.commentTxt) {
            cell.spotContent.text=self.commentTxt;
        }
        else{
        cell.btn1.hidden=YES;
        [cell.spotContent setTextColor:[UIColor lightGrayColor]];
        }
    }
    if (indexPath.row==3) {
        if (self.startDate) {
            NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSString *currentDate = [dateFormat stringFromDate:self.startDate];
            cell.spotContent.text=currentDate;
        }
    }
    if ([[self.selectText allKeys] containsObject:[NSString stringWithFormat:@"%i", indexPath.row]]) {
        [cell.spotContent setTextColor:[UIColor blackColor]];

    }
    //    cell.textLabel.textAlignment = NSTextAlignmentCenter;//文字居中
    //    cell.model=[RouteModel new];
    cell.block = ^(UIButton *sender) {
        [self.selectText setValue:@"" forKey:[NSString stringWithFormat:@"%i", sender.tag] ];
        switch (sender.tag) {
            case 0:
            {
                SpotSiteViewController * detailVC = [[SpotSiteViewController alloc]init];
                detailVC.block1 = ^(UserSites *data) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.titleArray replaceObjectAtIndex:0 withObject:data.siteName];
                        self.selectSite=data;

                        [tableView reloadData];
                    });
                };
                //        detailVC.model = self.aticleArray[indexPath.row];
                [self.rt_navigationController pushViewController:detailVC animated:YES];
            }
            break;
            case 1:
            {
                SpotPtiorityViewController * detailVC = [[SpotPtiorityViewController  alloc]init];
                detailVC.block1 = ^(NSString *data) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.titleArray replaceObjectAtIndex:1 withObject:data];

                        [tableView reloadData];
                    });
                };
                //        detailVC.model = self.aticleArray[indexPath.row];
                [self.rt_navigationController pushViewController:detailVC animated:YES];
            }
            break;
            case 2:
            {
                SpotUserViewController * detailVC = [[SpotUserViewController alloc]init];
                detailVC.selectSite=self.selectSite;
                detailVC.block1 = ^(UserInfo *data) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.titleArray replaceObjectAtIndex:2 withObject:data.userName];
                        self.selectUser=data;

                        [tableView reloadData];
                    });
                };
                //        detailVC.model = self.aticleArray[indexPath.row];
                [self.rt_navigationController pushViewController:detailVC animated:YES];
            }
            break;
            case 3:
            {
//                SpotCalenderViewController * detailVC = [[SpotCalenderViewController alloc]init];
//                //        detailVC.model = self.aticleArray[indexPath.row];
//                [self.rt_navigationController pushViewController:detailVC animated:YES];
                [LYSDatePickerController alertDatePickerInWindowRootVC];
                [LYSDatePickerController customPickerDelegate:self];
                [LYSDatePickerController customdidSelectDatePicker:^(NSDate *date) {
                    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
                    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
                    NSString *currentDate = [dateFormat stringFromDate:date];
                    SpotCreateViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.spotContent.text = currentDate;
                    self.startDate=date;

                    [tableView reloadData];

                }];
            }
            break;
            case 4:
            {
                SopTextViewController * detailVC = [[SopTextViewController alloc]init];
                //        detailVC.model = self.aticleArray[indexPath.row];
                if (self.commentTxt)
                    detailVC.saveText=self.commentTxt;
                [self.rt_navigationController pushViewController:detailVC animated:YES];
                detailVC.block = ^(NSString *txt) {
                    if ([txt isEqualToString:@"填写文本"]) {
                        
                    }
                    else
                    {
                        if (![txt isEqualToString:@""]) {
                            cell.spotContent.text=txt;
                            [cell.spotContent setTextColor:[UIColor blackColor]];
                        }
                        else{
                            cell.spotContent.text=@"请在此处输入";
                            [cell.spotContent setTextColor:[UIColor lightGrayColor]];
                        }
                        self.commentTxt=txt;

                    }
                };
            }
                break;
            default:
            break;
        }

    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 130;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
     NewsDetailViewController * detailVC = [[NewsDetailViewController alloc]init];
     detailVC.model = self.aticleArray[indexPath.row];
     [self.rt_navigationController pushViewController:detailVC animated:YES];
     */
    //    DetailViewController * detailVC = [[DetailViewController alloc]init];
    //    //    detailVC.model = self.aticleArray[indexPath.row];
    //    [self.rt_navigationController pushViewController:detailVC animated:YES];
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
//        tableView.separatorColor=[UIColor clearColor];
        tableView.tableFooterView = [UIView new];
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        view.backgroundColor = XMColor(241, 245, 247);
        UILabel* titleLabel = [[UILabel alloc]init];
        titleLabel.font = [UIFont xm_medium:17.0];
        titleLabel.numberOfLines = 1;
        titleLabel.textColor = [UIColor xm_jetblackColor];
        titleLabel.text=@"创建临时任务";
        
        [view addSubview:titleLabel];
        tableView.tableHeaderView=view;
//        UIView * viewFoot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
//        viewFoot.backgroundColor = [UIColor whiteColor];
//        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
//        //        button.frame = CGRectMake(40, 100, SCREEN_WIDTH- 80, 30);
//        button.backgroundColor = DGColor;
//        [button setTitle:@"创建" forState:UIControlStateNormal];
//        [button addTarget:self action:@selector(submitRoute) forControlEvents:UIControlEventTouchUpInside];
//        [viewFoot addSubview:button];
//        tableView.tableFooterView=viewFoot;
        //        [button setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
        //        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(18);
            make.left.equalTo(view.mas_left).offset(20);
        }];
        
//        [button mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.center.equalTo(viewFoot).offset(0);
//            //            make.top.equalTo(view).offset(5);
//            make.width.mas_equalTo(SCREEN_WIDTH-80);
//            make.height.mas_equalTo(50);
//            //            make.left.equalTo(view.mas_left).offset(20);
//        }];
        _tableView = tableView;
    }
    return _tableView;
}
-(void)submitRoute
{
    
}

@end
